package com.bwhx.eruler.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.bean.User;
import com.bwhx.eruler.bean.Version;
import com.bwhx.eruler.service.UserService;
import com.bwhx.eruler.service.VersionService;
import com.bwhx.eruler.util.MD5Utils;
import com.bwhx.eruler.util.StringUtils;

/**
 * 注册和登录对应的都是数据库的manager表 
 * 量体师
 * @author Cuilitang
 *
 */
@Controller
public class UserController extends BaseController {
	
	@Autowired
	UserService userService;
	
	@Autowired
	VersionService verService;

	@ResponseBody
	@RequestMapping(value = "/page.listRulerUser.ashx")
	 public Map<String,Object> selectRulerUser(Integer page,Integer rows,Integer rulerId, @RequestBody String b) {
		 log.info(b);
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,rulerId);
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			List<User> list = userService.listRulerUser(p);
			Integer i  = userService.countRulerUser(rulerId);
			log.info(list);
			log.info(rulerId);
			
			map.put("total",i );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			
			for (User u : list) {
				log.info(u);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	
	@ResponseBody
	@RequestMapping(value = "/page.userList.ashx")
	 public Map staffList(Integer page,Integer rows,User user, @RequestBody String b) {
		 log.info(b);
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,user);
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			List<User> list = userService.list(p);
			Integer i  = userService.count(user);
			log.info(list);
			log.info(user);
			
			map.put("total",i );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			
 			log.info("rows："+list.size());
 			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/UserReg.ashx",method={RequestMethod.POST})
	 public Map regist(HttpServletRequest request) {
		
		Map map = new HashMap();
		map.put("meg", "注册成功");
		map.put("status", "1");
		
		//判断用户名和密码是否为空
		String username = (String)request.getAttribute("username");
		log.info(username);
		String pwd = (String)request.getAttribute("pwd");
		String mobile = (String) request.getAttribute("mobile");
		String email = (String) request.getAttribute("email");
		String qq = (String) request.getAttribute("qq");
		String devsys = (String) request.getAttribute("devsys");
		String devModel = (String)request.getAttribute("devmodel");
		String sysVersion = (String)request.getAttribute("sysversion");
		String countryCode = (String)request.getAttribute("countrycode");
		
		try{
			
			if(StringUtils.isEmpty(username)){
				map.put("meg", "用户名不能为空！");
				map.put("status", "0");
				return map;
			}
			if(StringUtils.isEmpty(pwd)){
				map.put("meg", "密码不能为空！");
				map.put("status", "0");
				return map;
			}
	
		/*	if(StringUtils.isEmpty(mobile)||!StringUtils.checkMobile(mobile)){
				map.put("meg", "请检查您的手机号输入信息！");
				map.put("status", "0");
				return map;
			}*/
			/*
			if(StringUtils.isEmpty(email)||!StringUtils.checkEmail(email)){
				map.put("meg", "请检查您的电子邮箱输入信息！");
				map.put("status", "0");
				return map;
			}
			*/
			
			//判断用户名是否重复
			List<User> users = userService.findByName(username);
			if(users.size()>0){
				map.put("meg", "用户名重复，请使用其他用户名！");
				map.put("status", "0");
				return map;
			}
			
			//判断用户名是否重复
			List<User> users2 = userService.findByMoblie(mobile);
			if(users2.size()>0){
				map.put("meg", "您的手机号已经注册过，请使用重新设置密码功能！");
				map.put("status", "0");
				return map;
			}
			
			
			
			User user = new User();
			user.setUsername(username);
			user.setEmail(email);
			user.setMobile(mobile);
			user.setPwd(MD5Utils.md5(pwd));
			user.setQq(qq);
			user.setDevSys(devsys);
			user.setRegdatetime(System.currentTimeMillis()/1000);
			user.setDevModel(devModel);
			user.setSysVersion(sysVersion);
			user.setCountryCode(countryCode);
 			userService.insert(user);	
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "注册失败");
			map.put("status", "0");
		}
	    return map;  
	  }
	
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/UserLogin.ashx",method={RequestMethod.POST})
	 public Map login(HttpServletRequest request) {
		
		Map map = new HashMap();
		map.put("meg", "登录成功");
		map.put("status", "1");
		
		//判断用户名和密码是否为空
		String username = ((String)request.getAttribute("username"));
		String pwd = ((String)request.getAttribute("pwd"));
		
		if(StringUtils.isEmpty(username)){
			map.put("meg", "请输入用户名或者手机号！");
			map.put("status", "0");
			return map;
		}
		
		if(StringUtils.isEmpty(pwd)){
			map.put("meg", "请检查您的密码！");
			map.put("status", "0");
			return map;
		}
		
		User user = new User();
		user.setUsername(username);
		user.setPwd(MD5Utils.md5(pwd));	
		
		try{
					
			List<User> userBack = userService.find(user);
			if(userBack==null||userBack.size()==0){
				map.put("meg", "请检查您的用户名和密码是否正确！");
				map.put("status", "0");
			}else{
				User user2 = userBack.get(0);
				user2.setPwd("");
				
				map.put("userinfo", user2);
			
			
				/*
				 这两个字段不要了，因为app只是第一次需要登录，以后就不需要登录了
				Map<String,Object> mapupdate = new HashMap<String,Object>();
				mapupdate.put("id", user2.getId());
				if(user2.getCountLogin()!=null){
					mapupdate.put("countlogin", user2.getCountLogin()+1);
				}else{
					mapupdate.put("countlogin",1);
				}
				
				mapupdate.put("lltime", System.currentTimeMillis()/1000);
				userService.update(mapupdate); 
				*/
				
			}
						
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "请求异常！");
			map.put("status", "0");
		}
	    return map;  
	  }
	
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/updateUser.ashx",method={RequestMethod.POST})
	 public Map updateUser(HttpServletRequest request) {
		
		Map map = new HashMap();
		map.put("meg", "修改成功");
		map.put("status", "1");
		//判断用户名和密码是否为空
		Integer id = Integer.parseInt(request.getAttribute("id").toString().replace("\"", ""));
		String username = ((String)request.getAttribute("username"));
		String mobile = ((String)request.getAttribute("mobile"));
		String pwd = ((String)request.getAttribute("pwd"));
		String oldPwd = ((String)request.getAttribute("oldpwd"));

		
		User user = new User();
		user.setId(id);
		
		if(!StringUtils.isEmpty(username)){
			user.setUsername(username);
			if(userService.findByName(username).size()>0){
				map.put("meg", "用户名重复");
				map.put("status", "0");
				return map;
			}
		}
		if(!StringUtils.isEmpty(mobile)){
			user.setMobile(mobile);	
			List<User> findByMoblie = userService.findByMoblie(mobile);
			if(findByMoblie.size()>0){
				map.put("meg", "手机号重复");
				map.put("status", "0");
				return map;
			}
		}
		if(!StringUtils.isEmpty(pwd)){
			user.setPwd(MD5Utils.md5(pwd));	
		}
		try{
			
			if(!StringUtils.isEmpty(oldPwd)){
				User user1 = userService.find(id);
				
				if(user1==null){
					map.put("meg", "无此用户！");
					map.put("status", "0");
					return map;
				}
				if(!user1.getPwd().equals(MD5Utils.md5(oldPwd))){
					map.put("meg", "原密码错误！");
					map.put("status", "0");
					return map;
				}
			}
			
			userService.update(user);
			
						
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "请求异常！");
			map.put("status", "0");
		}
	    return map;  
	  }
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/updateUserForgetPwd.ashx",method={RequestMethod.POST})
	 public Map updateUserForgetPwd(HttpServletRequest request) {
		
		Map map = new HashMap();
		map.put("meg", "重置密码成功");
		map.put("status", "1");
		
		//判断用户名和密码是否为空
		String mobile = ((String)request.getAttribute("mobile"));
		String pwd = ((String)request.getAttribute("pwd"));
		
		User user = new User();
		
		
		if(!StringUtils.isEmpty(mobile)){
			user.setMobile(mobile);	
			List<User> findByMoblie = userService.findByMoblie(mobile);
			if(findByMoblie.size()==0){
				map.put("meg", "手机号未注册");
				map.put("status", "0");
				return map;
			}
		}
		if(!StringUtils.isEmpty(pwd)){
			user.setPwd(MD5Utils.md5(pwd));	
		}
		
		try{
			userService.updateByMobile(user);
			
						
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "系统错误！");
			map.put("status", "-1");
		}
	    return map;  
	  }
}
